<?php
 /**
 * Demand save
 * 
 * @author: trungdt
 * @since: Feb 2, 2011
 * @version: 1.0
 * 
 * Change logs
 * Feb 2, 2011 - trungdt - first create
 * Feb 6, 2011 - trungdt - move all saving actions into modeller
 * Feb 25, 2011 - trungdt - Support Item index for search
 */
if (!defined("EXPONENT")) exit("");
    $demand = null;        
    // build localtion
    $loc=null;
    $loc->mod="demandmodule";
    
    if (isset($_POST['id'])) {
        $demand = $db->selectObject('demands', 'id='.intval($_POST['id']));
    } else {
        
    }
    
    //if (exponent_permissions_check("manage",$loc)) {   
    // we can continue if 
    // - this user has administrate or approve demand permission
    // - this user is the owner of this record (post new) 
    if ((
    (exponent_permissions_check("administrate",$loc) ||
     exponent_permissions_check("approve_demand",$loc)) && 
     isset($demand->id)
    ) 
    || 
    ((!isset($demand->id)) && exponent_users_isLoggedIn())
    )  {
      
      // check captcha
      if (!isset($demand->id))
      {
          //validator::validate(array('captcha'=>'captcha_string'), $_POST);
          $captcha_real = exponent_sessions_get('captcha_string');
          if (isset($_POST['captcha_string']) && (strtolower($_POST['captcha_string']) == strtolower($captcha_real)))
          {
              exponent_sessions_unset("captcha_string");
          }
          else
          {
              // show error: captcha not regconize
              die(exponent_lang_getText("captcha_not_the_same"));
          }
      }
        
      $demand= demands::update($_POST, $demand);
      
      // end of calculate
      // again we check permission
      if (isset($demand->id)  && 
      (
        exponent_permissions_check("administrate",$loc) || 
        exponent_permissions_check("approve_demand",$loc)
      )
      ) {
          $db->updateObject($demand,"demands");
      } else {
          // save ID for later use :)
          $demand->id=$db->insertObject($demand,"demands");
      }
      // end 
      //exponent_flow_redirect(SYS_FLOW_ACTION);
      //redirect_to($url);
      // Feb 25, 2011 - index this item - begin
      demandmodule::ab_spiderItem($demand);
      // Feb 25, 2011 - index this item - end
      $tlink="";
      /*if (exponent_javascript_inAjaxAction())
      {
        $params=array(
            'action'=>'my-demand',
            'module'=>'demandmodule'
          );
          $tlink=exponent_core_makeLink($params);
          $tlink.=
      }
      else*/
        $tlink=exponent_flow_get()."#".$demand->id."-"._to_vietnamese_with_nomark($demand->name);
      echo "OK".$tlink;
    } else {
        echo SITE_403_HTML;
    }
    

?>
